package com.zfast.config.service.Impl;

import com.zfast.config.entity.Role;
import com.zfast.config.repository.RoleRepository;
import com.zfast.config.service.RoleService;
import com.zfast.config.vo.PageBean;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Classname RoleServiceImpl
 * @Description None
 * @Date 2019/7/18 8:36
 * @Created by WDD
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    RoleRepository roleRepository;

    @Override
    public List<Role> selectAll() {
        return roleRepository.findAll();
    }

    @Override
    public PageBean<Role> queryPage(Map<String, Object> paramMap) {
        PageBean<Role> pageBean = new PageBean<>((Integer) paramMap.get("pageno"), (Integer) paramMap.get("pagesize"));

        Integer pageno = (Integer) paramMap.get("pageno") - 1;
        Integer pagesize = (Integer) paramMap.get("pagesize");

        Page<Role> all = roleRepository.findAll(PageRequest.of(pageno, pagesize));

        pageBean.setDatas(all.getContent());
        pageBean.setTotalsize((int) all.getTotalElements());
        return pageBean;
    }

    @Override
    @Transactional
    public int delByRoleIds(List<String> ids) {
        //zgnTodo 关联用户
        roleRepository.deleteAllByIdInBatch(ids);
        return ids.size();
        /*//存在管理员拥有此角色，无法删除
        return 0;*/
    }

    @Override
    public Role selectById(String id) {
        return roleRepository.findById(id).orElse(null);
    }

    @Override
    public Role selectByName(String name) {
        Role role = Role.builder().name(name).build();
        Example<Role> userExample = Example.of(role);
        return roleRepository.findOne(userExample).orElse(null);
    }

    @Override
    public int editByRole(Role role) {
        roleRepository.save(role);
        return 1;
    }

    @Override
    public int insertRole(Role role) {
        roleRepository.save(role);
        return 1;
    }
}
